網頁不只是用來看的,使用者也需要與它互動。表單(Form)就是這種互動的核心,它可以讓使用者可以輸入資料、傳送訊息。今天學習如何建立一個簡單的聯絡表單。
表單的基本標籤:
<form>
: 表單容器,所有表單元素都放在這裡。<label>
: 表單元素的標籤,點擊它會聚焦到相關的輸入框。<input>
: 輸入框,有很多種 type,如 text (文字)、email、password 等。<textarea>
: 多行文字輸入框,適合長篇訊息。<button>
: 按鈕,用來提交表單。製作一個聯絡表單。
在 index.html 中:
HTML
<form>
<label for="name">姓名:</label>
<input type="text" id="name" name="name" />
<label for="email">電子郵件:</label>
<input type="email" id="email" name="email" />
<label for="message">訊息:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">送出</button>
</form>
在 style.css 中:
CSS
form {
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
input,
textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
box-sizing: border-box; /* 避免內邊距和邊框增加寬度 */
}
button {
background-color: #2c3e50;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
這個表單現在看起來很簡單,但它已經具備了基本的互動功能。之後還需要後端程式來處理這些資料,前端的部分已經完成。
執行成果 :